package com.edu.pic.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.edu.entity.HfdPicStatic;
import com.edu.pic.mapper.HfdPicStaticMapper;
import com.edu.pic.service.IHfdPicStaticService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.edu.vo.Result;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 静态化图片表 服务实现类
 * </p>
 *
 * @author zy
 * @since 2021-04-15
 */
@Service
public class HfdPicStaticServiceImpl extends ServiceImpl<HfdPicStaticMapper, HfdPicStatic> implements IHfdPicStaticService {
    @Autowired
    private HfdPicStaticMapper hfdPicStaticMapper;

    @Override
    public Result indexPicToFtl() {
        try {
            //1.构建Configuration对象
            Configuration configuration = new Configuration(Configuration.getVersion());
            //2.设置模板文件目录(Directory)
            configuration.setDirectoryForTemplateLoading(new File("D:\\workidea\\houfudao-test\\edu-index\\src\\main\\resources"));
            //3.设置字符集
            configuration.setDefaultEncoding("utf-8");
            //4.获取模板对象
            Template template = configuration.getTemplate("templates/index.ftl");
            //5.创建模型数据
            QueryWrapper queryWrapper = new QueryWrapper();
            List<HfdPicStatic> pics = hfdPicStaticMapper.selectList(queryWrapper);
            Map data = new HashMap();
            pics.forEach(pic -> {
                data.put(pic.getType(), pic);
            });
            //6.创建输出流(Writer)对象
            Writer out = new FileWriter("C:\\Users\\12719\\Desktop\\nginx-1.18.0\\pages\\index.html");
            //7.输出
            template.process(data, out);
            //8.关闭
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, 0, "静态化失败");
        }
        return new Result(true, 1, "静态化成功");
    }
}
